package com.ruoyi.cs.service.impl;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.Response;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.cs.domain.*;
import com.ruoyi.cs.domain.vo.VIPInfoVo;
import com.ruoyi.cs.mapper.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.cs.service.ITVipGradeService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

/**
 * 【请填写功能名称】Service业务层处理
 * 
 * @author ruoyi
 * @date 2023-03-02
 */
@Service
@SuppressWarnings("all")
public class TVipGradeServiceImpl implements ITVipGradeService 
{
    @Autowired
    private TVipGradeMapper tVipGradeMapper;
    @Autowired
    private TUserMapper tUserMapper;
    @Autowired
    private TVipReceiveMapper tVipReceiveMapper;
    @Autowired
    private TRechargeMapper tRechargeMapper;
    @Autowired
    private TBalanceChangeMapper tBalanceChangeMapper;
    @Autowired
    private TVipUserMapper tVipUserMapper;

    /**
     * 查询【请填写功能名称】
     * 
     * @param id 【请填写功能名称】主键
     * @return 【请填写功能名称】
     */
    @Override
    public TVipGrade selectTVipGradeById(Long id)
    {
        return tVipGradeMapper.selectTVipGradeById(id);
    }

    /**
     * 查询【请填写功能名称】列表
     * 
     * @param tVipGrade 【请填写功能名称】
     * @return 【请填写功能名称】
     */
    @Override
    public List<TVipGrade> selectTVipGradeList(TVipGrade tVipGrade)
    {
        return tVipGradeMapper.selectTVipGradeList(tVipGrade);
    }

    /**
     * 新增【请填写功能名称】
     * 
     * @param tVipGrade 【请填写功能名称】
     * @return 结果
     */
    @Override
    public int insertTVipGrade(TVipGrade tVipGrade)
    {
        tVipGrade.setCreateTime(DateUtils.getNowDate());
        return tVipGradeMapper.insertTVipGrade(tVipGrade);
    }

    /**
     * 修改【请填写功能名称】
     * 
     * @param tVipGrade 【请填写功能名称】
     * @return 结果
     */
    @Override
    public int updateTVipGrade(TVipGrade tVipGrade)
    {
        tVipGrade.setUpdateTime(DateUtils.getNowDate());
        return tVipGradeMapper.updateTVipGrade(tVipGrade);
    }

    /**
     * 批量删除【请填写功能名称】
     * 
     * @param ids 需要删除的【请填写功能名称】主键
     * @return 结果
     */
    @Override
    public int deleteTVipGradeByIds(Long[] ids)
    {
        return tVipGradeMapper.deleteTVipGradeByIds(ids);
    }

    /**
     * 删除【请填写功能名称】信息
     * 
     * @param id 【请填写功能名称】主键
     * @return 结果
     */
    @Override
    public int deleteTVipGradeById(Long id)
    {
        return tVipGradeMapper.deleteTVipGradeById(id);
    }

    /**
     * 获取当前最大VIP
     * @return
     */
    @Override
    public int getMaxVip() {
        return tVipGradeMapper.getMaxVip();
    }

    /**
     * 个人VIP会员中心
     * @param userId
     * @return
     */
    @Override
    public Response<VIPInfoVo> myVipInfo(String userId) {
        List<TVipGrade> tVipGradeList = tVipGradeMapper.getVipList();
        VIPInfoVo vipInfoVo = new VIPInfoVo();
        if(userId == null){
            /**未登录情况下*/
            vipInfoVo.setTVipGradeList(tVipGradeList);
            return Response.success(vipInfoVo);
        }

        TUser tUser = tUserMapper.selectTUserById(userId);
        long userVip = tUser.getUserVip();
        if(!CollectionUtils.isEmpty(tVipGradeList)){
            /**设置VIP等级的领取状态*/
            List<TVipReceive> tVipReceiveList = tVipReceiveMapper.getVipReceiveByUserId(userId);
            for (TVipGrade tVipGrade : tVipGradeList) {
                long num = tVipReceiveList.stream().filter(bean -> bean.getVip().equals(tVipGrade.getVip())).count();
                if(num > 0){
                    tVipGrade.setReceiveStatus("0");
                }else {
                    if(userVip >= tVipGrade.getVip().longValue()){
                        tVipGrade.setReceiveStatus("1");
                    }else {
                        tVipGrade.setReceiveStatus("2");
                    }
                }
            }
        }
        /**设置用户VIP和VIP等级列表*/
        vipInfoVo.setVip(userVip);
        vipInfoVo.setTVipGradeList(tVipGradeList);
        /**当前成长值*/
        vipInfoVo.setCurryGrowthValue(tUser.getConsumeValue());
        /**当前最高VIP等级*/
        long maxvip = tVipGradeList.get(tVipGradeList.size()-1).getVip();
        vipInfoVo.setMaxVip(maxvip);
        /**所需成长值*/
        long nextVip = userVip+1;

        if(nextVip > maxvip){
            vipInfoVo.setNeedGrowthValue(BigDecimal.valueOf(0));
        }else {
            TVipGrade tVipGrade = tVipGradeList.stream().filter(bean -> bean.getVip().longValue() == nextVip).findFirst().get();
            BigDecimal threshold = tVipGrade.getThreshold();
            vipInfoVo.setNeedGrowthValue(threshold.subtract(tUser.getConsumeValue()));
        }
        return Response.success(vipInfoVo);
    }

    /**
     * VIP等级奖励领取
     * @param userId
     * @param vip
     * @return
     */
    @Override
    @Transactional
    public Response receive(String userId, long vip) {
        if(vip == 0){
            return Response.fail("会员等级0无奖励可领!");
        }
        TUser tUser = tUserMapper.selectTUserById(userId);
        if (tUser == null || !Constants.SUCCESS.equals(tUser.getDelFlag())) {
            return Response.fail("账号不存在或已被冻结!");
        }
        long userVip = tUser.getUserVip();
        if(userVip < vip){
            return Response.fail("当前会员等级不足，无法领取!");
        }
        long isReceive = tVipReceiveMapper.isReceive(userId,vip);
        if(isReceive > 0){
            return Response.fail("该会员等级奖励已领取过!");
        }
        List<TVipGrade> tVipGradeList = tVipGradeMapper.getVipList();
        Optional<TVipGrade> optionalTVipGrade = tVipGradeList.stream().filter(bean -> bean.getVip().longValue() == vip).findFirst();
        if(!optionalTVipGrade.isPresent()){
            return Response.fail("无对应会员等级!");
        }
        TVipGrade tVipGrade = optionalTVipGrade.get();
        BigDecimal userBlance = tUser.getUserBalance();
        /**领取奖励至用户余额*/
        tUser.setUserBalance(userBlance.add(tVipGrade.getVipReward()));
        int row = tUserMapper.updateTUserBalance(tUser);
        if(row < 1){
            return Response.fail("领取失败，请重试!");
        }

        TVipReceive tVipReceive = new TVipReceive();
        tVipReceive.setUserId(userId);
        tVipReceive.setVip(vip);
        tVipReceive.setVipReward(tVipGrade.getVipReward());
        tVipReceive.setCreateTime(DateUtils.getNowDate());
        tVipReceiveMapper.insertTVipReceive(tVipReceive);

        /**余额变更记录表*/
        TBalanceChange balanceChange = new TBalanceChange();
        balanceChange.setUserId(userId);
        balanceChange.setBalanceBefore(userBlance);
        balanceChange.setBalanceAfter(tUser.getUserBalance());
        balanceChange.setOperationType(Constants.OPERATIONTYPE11);
        balanceChange.setFrequency(1);
        balanceChange.setFee(tVipGrade.getVipReward());
        balanceChange.setCorrespondingid(tVipReceive.getId().toString());
        balanceChange.setCreateTime(DateUtils.getNowDate());
        balanceChange.setProfitPrice(tVipGrade.getVipReward());
        balanceChange.setSecondCurrencyBefore(tUser.getSecondCurrency());
        balanceChange.setSecondCurrencyAfter(tUser.getSecondCurrency());
        tBalanceChangeMapper.insertTBalanceChange(balanceChange);
        return Response.success("领取成功");
    }

    /**
     * 会员特权列表
     * @return
     */
    @Override
    public List<TVipGrade> vipList() {
        List<TVipGrade> tVipGradeList = tVipGradeMapper.getVipList();
        return tVipGradeList;
    }
    /**
     * 充值页面显示的所需充值和额外奖励领取计算
     * @param userId
     * @return
     */
    @Override
    public Response<Map> computeVip(String userId) {
        TUser tUser = tUserMapper.selectTUserById(userId);
        long vip = tUser.getUserVip();
        long nextVip = vip+1;
        TVipGrade tVipGrade = tVipGradeMapper.getUserVip(nextVip);
        BigDecimal threshold = tVipGrade.getThreshold();

        Map map = new HashMap();
        map.put("needCzMoney",threshold.subtract(tUser.getConsumeValue()));
        map.put("reward",tVipGrade.getVipReward());
        return Response.success(map);
    }

    /**
     * VIP过期处理，对超过30天VIP级别没变更的会员进行处理
     * @param userId
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Response VipExpire(String userId,List<TVipGrade> tVipGradeList) {
        TUser tUser = tUserMapper.selectTUserById(userId);
        /**当前等级*/
        long vip = tUser.getUserVip();
        Optional<TVipGrade> optional1 = tVipGradeList.stream().filter(bean -> vip == bean.getVip().longValue()).findFirst();
        if(!optional1.isPresent()){
            return Response.fail("未找到对应等级");
        }
        TVipGrade tVipGrade = optional1.get();
        /**上等级*/
        long uppervip = vip-1;
        TVipGrade uppertVipGrade = null;
        if(uppervip > 0){
            Optional<TVipGrade> optional2 = tVipGradeList.stream().filter(bean -> uppervip == bean.getVip().longValue()).findFirst();
            if(!optional2.isPresent()){
                return Response.fail("未找到对应等级");
            }
            uppertVipGrade = optional2.get();
        }

        BigDecimal relegationRechar = (tVipGrade.getThreshold().subtract(uppertVipGrade == null ? BigDecimal.ZERO : uppertVipGrade.getThreshold())).divide(BigDecimal.valueOf(2),2);
        /**是否保级操作*/
        boolean relegationFlag = true;
        if(tUser.getRelegationValue().compareTo(relegationRechar) < 0){
            /**降级操作*/
            relegationFlag = false;
            tUser.setUserVip(tUser.getUserVip()-1);
            tUser.setVipValue(uppertVipGrade == null ? BigDecimal.ZERO :uppertVipGrade.getThreshold());
        }
        /**不管降级或者保级，保级充值都置0*/
        tUser.setRelegationValue(BigDecimal.valueOf(0));
        int row1 = tUserMapper.updateTUserToRecharge(tUser);
        if(row1 < 1){
            throw new CustomException("更新用户失败!");
        }
        /**插入等级变更记录*/
        TVipUser tVipUser = new TVipUser();
        tVipUser.setUserId(tUser.getUserId());
        tVipUser.setGoVip(vip);
        tVipUser.setNowVip(relegationFlag ? vip : uppervip);
        tVipUser.setVipStatus(relegationFlag ? "1" : "2");
        tVipUser.setCreateTime(DateUtils.getNowDate());
        tVipUserMapper.insertTVipUser(tVipUser);
        return Response.success();
    }
    /**
     * 获取所有VIP用户等级过期的用户数据
     * @param time
     * @return
     */
    @Override
    public List<Map> allVipUserExpire() {
        String time = Constants.curryVIPCzStartTime;
        return tVipGradeMapper.allVipUserExpire(time);
    }
}
